package org.example.servlet;

import org.example.entity.UContent;
import org.example.entity.Review;
import org.example.entity.Reply;
import org.example.entity.User;
import org.example.service.*;
import org.example.service.UContentService;
import org.example.service.ReviewService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/content/detail")
public class UContentDetailServlet extends HttpServlet {
    private final UContentService uContentService = new UContentService();
    private final ReviewService reviewService = new ReviewService();
    private final FavoriteService favoriteService = new FavoriteService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 1. 获取请求参数并验证
            String type = req.getParameter("type");
            int id = Integer.parseInt(req.getParameter("id"));

            if (type == null || (!type.equals("movie") && !type.equals("book") && !type.equals("music"))) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的内容类型");
                return;
            }

            // 2. 获取内容详情
            UContent content = uContentService.getContentById(id);
            if (content == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到指定内容");
                return;
            }

            // 3. 验证内容类型是否匹配
            if (!content.getType().equals(type)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "内容类型不匹配。请求类型: " + type + "，实际类型: " + content.getType());
                return;
            }

            // 4. 获取评论及回复
            List<Review> reviews = reviewService.getReviewsByContent(id, type);
            for (Review review : reviews) {
                List<Reply> replies = reviewService.getRepliesByReview(review.getId());
                review.setReplies(replies);
            }

            // 5. 检查收藏状态
            if (req.getSession(false) != null && req.getSession(false).getAttribute("user") != null) {
                User user = (User) req.getSession(false).getAttribute("user");
                boolean isFavorite = favoriteService.isFavorite(user.getId(), content.getId(), content.getType());
                req.setAttribute("isFavorite", isFavorite);
            }

            // 6. 设置请求属性
            req.setAttribute("content", content);
            req.setAttribute("reviews", reviews);
            req.setAttribute("contentType", type);

            // 7. 转发到JSP页面
            req.getRequestDispatcher("/content-detail.jsp").forward(req, resp);

        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的内容ID格式");
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "数据库错误: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "服务器错误: " + e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 处理添加评论的POST请求
            if (req.getParameter("action") != null && req.getParameter("action").equals("addComment")) {
                addComment(req, resp);
            }
            // 处理添加回复的POST请求
            else if (req.getParameter("action") != null && req.getParameter("action").equals("addReply")) {
                addReply(req, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
        }
    }

    private void addComment(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            // 检查用户是否登录
            if (req.getSession().getAttribute("user") == null) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请先登录");
                return;
            }

            // 获取表单数据
            int contentId = Integer.parseInt(req.getParameter("contentId"));
            String contentType = req.getParameter("contentType");
            String content = req.getParameter("content");
            int rating = Integer.parseInt(req.getParameter("rating"));

            // 创建评论对象
            Review review = new Review();
            review.setContentId(contentId);
            review.setContentType(contentType);
            review.setUserId(((User)req.getSession().getAttribute("user")).getId());
            review.setUsername(((User)req.getSession().getAttribute("user")).getUsername());
            review.setContent(content);
            review.setRating(rating);

            // 添加评论
            boolean success = reviewService.addReview(review);

            if (success) {
                resp.sendRedirect(req.getContextPath() + "/content/detail?id=" + contentId + "&type=" + contentType);
            } else {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加评论失败");
            }
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的参数格式");
        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
        }
    }

    private void addReply(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            // 检查用户是否登录
            if (req.getSession().getAttribute("user") == null) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请先登录");
                return;
            }

            // 获取表单数据
            int reviewId = Integer.parseInt(req.getParameter("reviewId"));
            String replyContent = req.getParameter("content");

            // 创建回复对象
            Reply reply = new Reply();
            reply.setReviewId(reviewId);
            reply.setUserId(((User)req.getSession().getAttribute("user")).getId());
            reply.setUsername(((User)req.getSession().getAttribute("user")).getUsername());
            reply.setContent(replyContent);

            // 添加回复
            boolean success = reviewService.addReply(reply);

            if (success) {
                // 获取原评论以重定向回正确的内容页
                Review review = reviewService.getReviewById(reviewId);
                resp.sendRedirect(req.getContextPath() + "/content/detail?id=" + review.getContentId() + "&type=" + review.getContentType());
            } else {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加回复失败");
            }
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的参数格式");
        } catch (SQLException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
        }
    }
}